using AutoMapper;
using Microsoft.Extensions.Logging;
using ORS.OrderRobot.Domain;
using ORS.OrderRobot.IOC;
using ORS.OrderRobot.ServiceContracts;
using ORS.OrderRobot.ServiceContracts.Dtos;
using System.Security.Cryptography;
using System.Text;

namespace ORS.OrderRobot.Service
{
    public class AdminService : IAdminService, IScoped
    {
        private readonly ILogger<AdminService> _logger;
        private readonly IRepository<Admin, int> _adminRepository;
        private readonly IJwtService _jwtService;
        private readonly IMapper _mapper;

        public AdminService(
            ILogger<AdminService> logger,
            IRepository<Admin, int> adminRepository,
            IJwtService jwtService,
            IMapper mapper)
        {
            _logger = logger;
            _adminRepository = adminRepository;
            _jwtService = jwtService;
            _mapper = mapper;
        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>登录结果</returns>
        public async Task<AdminLoginResult> LoginAsync(string username, string password)
        {
            var admin = await _adminRepository.GetAsync(x => x.Username == username);
            if (admin == null)
            {
                return new AdminLoginResult { Success = false, Message = "用户名或密码错误" };
            }

            var hashedPassword = HashPassword(password);
            if (admin.PasswordHash != hashedPassword)
            {
                return new AdminLoginResult { Success = false, Message = "用户名或密码错误" };
            }

            // 更新最后登录时间
            admin.LastLoginTime = DateTime.Now;
            await _adminRepository.UpdateAsync(admin);

            var adminDto = _mapper.Map<AdminDto>(admin);
            // 生成JWT Token
            var token = _jwtService.GenerateToken(adminDto);

            return new AdminLoginResult
            {
                Success = true,
                Token = token,
                Admin = adminDto
            };
        }

        /// <summary>
        /// 创建管理员
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="role">角色</param>
        /// <returns>创建结果</returns>
        public async Task<AdminCreateResult> CreateAdminAsync(string username, string password, string role = "User")
        {
            var existingAdmin = await _adminRepository.GetAsync(x => x.Username == username);
            if (existingAdmin != null)
            {
                return new AdminCreateResult { Success = false, Message = "用户名已存在" };
            }

            var hashedPassword = HashPassword(password);
            var admin = new Admin
            {
                Username = username,
                Password = password, // 保留明文密码用于兼容
                PasswordHash = hashedPassword,
                Role = role,
                CreatedTime = DateTime.Now
            };

            await _adminRepository.InsertAsync(admin);

            return new AdminCreateResult
            {
                Success = true,
                Admin = new AdminDto
                {
                    Id = admin.Id,
                    Username = admin.Username,
                    Role = admin.Role,
                    CreatedTime = admin.CreatedTime
                }
            };
        }

        /// <summary>
        /// 获取管理员信息
        /// </summary>
        /// <param name="id">管理员ID</param>
        /// <returns>管理员信息</returns>
        public async Task<AdminDto?> GetAdminAsync(int id)
        {
            var admin = await _adminRepository.GetAsync(id);
            if (admin == null)
            {
                return null;
            }

            return new AdminDto
            {
                Id = admin.Id,
                Username = admin.Username,
                Role = admin.Role,
                LastLoginTime = admin.LastLoginTime,
                CreatedTime = admin.CreatedTime
            };
        }

        /// <summary>
        /// 哈希密码
        /// </summary>
        /// <param name="password">明文密码</param>
        /// <returns>哈希后的密码</returns>
        private string HashPassword(string password)
        {
            using var sha256 = SHA256.Create();
            var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
            return Convert.ToBase64String(hashedBytes);
        }
    }
} 